//
// Created by Administrator on 2024/11/4.
//

#ifndef V8_BLOCK_QUEUE_H
#include <queue>

template<typename T>
class BlockingQueue {
private:
    std::queue<T> queue_;
    std::mutex mtx_;
    std::condition_variable not_empty_;
    std::condition_variable not_full_;
    size_t capacity_;

public:
    BlockingQueue(size_t capacity) : capacity_(capacity) {}

    void enqueue(T item) {
        std::unique_lock<std::mutex> lock(mtx_);
        while (queue_.size() >= capacity_) {
            not_full_.wait(lock);
        }
        queue_.push(item);
        not_empty_.notify_one();
    }

    T dequeue() {
        std::unique_lock<std::mutex> lock(mtx_);
        while (queue_.empty()) {
            not_empty_.wait(lock);
        }
        T item = queue_.front();
        queue_.pop();
        not_full_.notify_one();
        return item;
    }
};
#define V8_BLOCK_QUEUE_H

#endif //V8_BLOCK_QUEUE_H
